
#include "unixHeader.h"
#include "user.srpc.h"
#include <workflow/WFFacilities.h>
#include <workflow/MySQLMessage.h>
#include <workflow/MySQLResult.h>

#include <iostream>
using std::cout;
using std::endl;

using namespace srpc;

static WFFacilities::WaitGroup wait_group(1);

void sig_handler(int signo)
{
	wait_group.done();
}

class UserServiceServiceImpl : public UserService::Service
{
public:

	void Signup(ReqSignup *request, RespSignup *response, srpc::RPCContext *ctx) override
    {
        //1. 解析请求
        std::string username = request->username();
        std::string password = request->password();
        //2. 对数据进行处理
        std::string salt("12345678");
        std::string encodedpasswd(crypt(password.c_str(), salt.c_str()));
        std::string mysqlurl("mysql://root:1234@localhost");
        auto mysqlTask = WFTaskFactory::create_mysql_task(mysqlurl, 10, 
            [response](WFMySQLTask * mysqltask){
                cout << "mysqlCallback is running" << endl;
                //错误的检测
                int state = mysqltask->get_state();
                int error = mysqltask->get_error();
                cout << "state:" << state << endl;
                if(state != WFT_STATE_SUCCESS) {
                    printf("occurs error: %s\n", WFGlobal::get_error_string(state, error));
                    return;
                }
                //语法的检测
                auto mysqlresp = mysqltask->get_resp();
                if(mysqlresp->get_packet_type() == MYSQL_PACKET_ERROR) {
                    printf("ERROR %d, %s\n", mysqlresp->get_error_code(),
                           mysqlresp->get_error_msg().c_str());
                    return;
                }

                protocol::MySQLResultCursor cursor(mysqltask->get_resp());
                if(cursor.get_cursor_status() == MYSQL_STATUS_OK && 
                   cursor.get_affected_rows() == 1) {
                    //完成了写操作
                    response->set_code(0);
                    response->set_msg("SUCCESS");
                } else {
                    response->set_code(-1);
                    response->set_msg("failed");
                }
            });
        std::string sql("INSERT INTO cloudisk.tbl_user(user_name, user_pwd, status) VALUES('");
        sql += username + "','" + encodedpasswd + "', 0)";
        mysqlTask->get_req()->set_query(sql);
        ctx->get_series()->push_back(mysqlTask);
    } 
};

int main()
{
	GOOGLE_PROTOBUF_VERIFY_VERSION;
	unsigned short port = 1412;
	SRPCServer server;

	UserServiceServiceImpl userservice_impl;
	server.add_service(&userservice_impl);

	server.start(port);
	wait_group.wait();
	server.stop();
	google::protobuf::ShutdownProtobufLibrary();
	return 0;
}
